//
//  RootViewController.m
//  midiApp
//
//  Created by Laurent Novac on 17.02.11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------------------------*/

#import "RootViewController.h"
#import "RootView.h"
#import "TouchSurfaceView.h"
#import "Position.h"
#import "PositionQueue.h"
#import "PositionStack.h"
#include <unistd.h>

@implementation RootViewController
@synthesize touchSurface,xLabel,yLabel,rootView,normalizedPosition,repeatMode,positionQueue,positionStack,roundTripMode;

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------INIT--------------------------------------------------------------------------------------------------*/

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
		normalizedPosition=[[Position alloc]init];//other allocation made by IB
		positionQueue=[[PositionQueue alloc]init];
		positionStack=[[PositionStack alloc]init];
    }
    return self;
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------VIEW DID LOAD-----------------------------------------------------------------------------------------*/

- (void)viewDidLoad {
    [super viewDidLoad];
	[rootView setBackgroundColor:[UIColor grayColor]];
	[touchSurface setBackgroundColor:[UIColor grayColor]];
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------USER TOUCHED THE SURFACE------------------------------------------------------------------------------*/

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
	UITouch *touch=[touches anyObject];
	if([touch view]==touchSurface){
		[positionQueue emptyQueue];//we want to empty the stack or the queue
		[positionStack emptyStack];
		Position* newPosition=[[Position alloc]init];
		[newPosition setPos:[touch locationInView:touchSurface]];
		[touchSurface setTPosition:newPosition];//set the position to the finger position
		[touchSurface setNeedsDisplay];//we redraw the surface
		
		[positionQueue pushToTail:newPosition]; //add it to the queue 
		[positionStack pushToHead:newPosition];//add it to the stack
		
		[normalizedPosition setPos:[self normalizeValue:[newPosition pos]]];//normalize the value
				
		[xLabel setText:[NSString stringWithFormat:@"x: %.2f",[normalizedPosition pos].x]];//log the normalize value on label
		[yLabel setText:[NSString stringWithFormat:@"y: %.2f",[normalizedPosition pos].y]];
		
		[newPosition release];
	}	
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------USER MOVED FINGER IN THE SURFACE----------------------------------------------------------------------*/

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
	UITouch *touch=[touches anyObject];
	if([touch view]==touchSurface){
		Position* newPosition=[[Position alloc]init];
		[newPosition setPos:[touch locationInView:touchSurface]];
		[touchSurface setTPosition:newPosition];//set the position to the finger position
		[touchSurface setNeedsDisplay];//we redraw the surface
		[normalizedPosition setPos:[self normalizeValue:[newPosition pos]]];//normalize the value
		
		[positionQueue pushToTail:newPosition]; //add it to the queue 
		[positionStack pushToHead:newPosition];//add it to the stack
		
		[xLabel setText:[NSString stringWithFormat:@"x: %.2f",[normalizedPosition pos].x]];
		[yLabel setText:[NSString stringWithFormat:@"y: %.2f",[normalizedPosition pos].y]];
		
		[newPosition release];
	}
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------USER REMOVED FINGER FROM THE SURFACE------------------------------------------------------------------*/

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{	
	if([repeatMode isOn]){//check if we are in repeat mode or roundtrip mode
		NSEnumerator* enumerator=[[positionQueue queue] objectEnumerator];
		while ((qPos=[enumerator nextObject])) {
			[self repeat];
			//TODO timer to send repeat message
			NSLog(@"Back");
		}
	}
	//TODO same code for roundTripMode
}


/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------NORMALIZE THE VALUE-----------------------------------------------------------------------------------*/

-(CGPoint)normalizeValue:(CGPoint)point{ //rule of three to put the values in the correct range, we keep only positive value and integer value 
	CGPoint normalizedPoint;
	if (point.x<=0.0) {//we want the min value to be 0
		normalizedPoint.x=0.0;
	}
	if(point.y<=0.0){
		normalizedPoint.y=0.0;
	}
	int maxX=TOUCH_SURFACE_WIDTH;
	int maxY=TOUCH_SURFACE_HEIGHT;
	int nMaxX=TOUCH_NORMALIZED_WIDTH;
	int nMaxY=TOUCH_NORMALIZED_HEIGHT;
	normalizedPoint.x=(int)(point.x*nMaxX/maxX);//cast!
	normalizedPoint.y=(int)(point.y*nMaxY/maxY);
	
	return normalizedPoint;
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------REPEAT MODE-------------------------------------------------------------------------------------------*/

-(void)repeat{//This signature is mandatory for timers
	NSLog(@"repeatMode\n");
	[touchSurface setTPosition:qPos];
	[touchSurface setNeedsDisplay];
	NSLog([NSString stringWithFormat:@"qPos-> x: %.2f y:%.2f\n",[qPos pos].x,[qPos pos].y]);
	NSLog([NSString stringWithFormat:@"TPos-> x: %.2f y:%.2f\n",[[touchSurface tPosition] pos].x,[[touchSurface tPosition] pos].y]);

	[normalizedPosition setPos:[self normalizeValue:[qPos pos]]];
	[xLabel setText:[NSString stringWithFormat:@"x: %.2f",[normalizedPosition pos].x]];
	[yLabel setText:[NSString stringWithFormat:@"y: %.2f",[normalizedPosition pos].y]];
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------ROUND TRIP MODE---------------------------------------------------------------------------------------*/

-(void)roundTrip:(NSTimer*)timer{
	NSLog(@"roundTripMode\n");
	[touchSurface setTPosition:qPos];
	[touchSurface setNeedsDisplay];
	NSLog([NSString stringWithFormat:@"qPos-> x: %.2f y:%.2f\n",[qPos pos].x,[qPos pos].y]);
	NSLog([NSString stringWithFormat:@"TPos-> x: %.2f y:%.2f\n",[[touchSurface tPosition] pos].x,[[touchSurface tPosition] pos].y]);
	
	[normalizedPosition setPos:[self normalizeValue:[qPos pos]]];
	[xLabel setText:[NSString stringWithFormat:@"x: %.2f",[normalizedPosition pos].x]];
	[yLabel setText:[NSString stringWithFormat:@"y: %.2f",[normalizedPosition pos].y]];
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------------------------*/

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------------------------*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
	[super didReceiveMemoryWarning];
	// Release any cached data, images, etc. that aren't in use.
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------------------------*/

- (void)viewDidUnload {
	[super viewDidUnload];
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------MEMORY MANAGEMENT-------------------------------------------------------------------------------------*/

- (void)dealloc {
	[touchSurface release];
	[xLabel release];
	[yLabel release];
	[rootView release];
	[repeatMode release];
	[roundTripMode release];
	[normalizedPosition release];
	[positionQueue release];
	[positionStack release];
	[super dealloc];
}

/*--------------------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------------------------*/

@end
